global class RejectGoodWebService {
    
     WebService static String postRejectOrder(Id id) {
        // SavePoint sp = Database.setSavePoint();
     try{  
   
   // 获取退货订单数据
      
       ExWarehouse__c  ro =    [select id, isdeleted, name, 
        createddate, createdbyid, lastmodifieddate, 
        lastmodifiedbyid, systemmodstamp, lastvieweddate,
        lastreferenceddate, account__c, bodyname__c, cbiztype__c, 
        cgeneralhid__c, ck__c, ckname__c, corpcode__c, corpname__c, currtypename__c, 
        custcode__c, custname__c, dbilldate__c, deptname__c, isfq__c,
        iszx__c, kpfs__c, memo__c, ntaxrate__c, sa03__c, sflx__c, xsqy__c,
        ywyname__c, zdkh__c, detailsize__c, isreturnorder__c, returnrelationexhouse__c, 
         approvaldate__c, ReturnRelationExhouse__r.Name,CreatedBy.Name,
         Applicant__c, Contact__c,ReturnReason__c ,returnTransportFee__c,ReturnOtherReason__c,
                                
        FinancialManager__r.Name,SubCompanyManager__r.Name,TransferNumber__c,invoiceNumber__c,isReturnInvoice__c 
                                from ExWarehouse__c where  Id =:id];
    
        
        //获取退货订单明细
        List<ExWarehouse_Detail__c> hasDetails = [select Id,Name,vbatchcode__c,Product__c,
                                                  ReturnNum__c ,Product__r.Name,Product__r.NCCode__c,Product__r.Model__c,
                                                  Product__r.Spec__c,Product__r.SerialNo__c
                                                  from ExWarehouse_Detail__c where ExWarehouse__c = :id] ;
        //获取用户信息
         User u = [select id,SubCompanyManager__r.name from User where id =: System.UserInfo.getUserId()];
        
         
        //保存要返回给调用者的数据集合
        List<Map<String,String>> datas = new List<Map<String,String>>();
        for(ExWarehouse_Detail__c r : hasDetails){
            Map<String,String> data = new Map<String,String>();
            //CRM数据
            data.put('id', ro.Id);//退货单id
            data.put('return_code', ro.Name);//退货单号
            //data.put('dept_manager', u.SubCompanyManager__r.name);//部门经理
            data.put('finance', ro.FinancialManager__r.Name);//财务部
            data.put('capproveid', ro.SubCompanyManager__r.Name);//子公司总经理-审核人
            data.put('transfer_number', ro.TransferNumber__c);//调拨单号
            data.put('invoice_number', ro.invoiceNumber__c);//发票号
            data.put('applicant', ro.Applicant__c);//申请人
            data.put('contact', ro.Contact__c);//联系人
            //data.put('contact_dept', ro.ContactDept__c);//联系人部门
            //data.put('contact_phone', ro.ContactPhone__c);//联系人电话
           // data.put('contact_post', ro.ContactPost__c);//联系人职务
            
            //data.put('contact_date', ro.ContactDate__c!=null?Utils.date2String(ro.ContactDate__c,Utils.DATETIME_FORMAT_STR):'');//联系日期(日期)
            data.put('returnreason', ro.ReturnReason__c);//退货原因 --> 备注
            data.put('nreturnfee',ro.returnTransportFee__c.format());//客户退回运费
            data.put('return_reason_other', ro.ReturnOtherReason__c);//其他原因说明 ??
            data.put('nnum', r.ReturnNum__c.format());//退货数量
            data.put('is_return_invoice', ro.isReturnInvoice__c ?'Y':'N');//是否退发票
            data.put('approved_date', ro.ApprovalDate__c!=null?Utils.date2String(ro.ApprovalDate__c,Utils.DATETIME_FORMAT_STR):'');//审核通过时间(日期时间)
            data.put('coperatorid',ro.CreatedBy.Name);//制单人
            data.put('ckcode',ro.ck__c);//仓库
            data.put('ckname',ro.ckname__c);//仓库
            data.put('ctransmodeid','');//运输方式
            //NC数据
            data.put('bid',r.Id);//子表id;
            data.put('invname', r.Product__r.Name);//产品名称
            data.put('invcode', r.Product__r.NCCode__c);//产品代码
            data.put('invtype', r.Product__r.Model__c);//产品型号
            data.put('invspec', r.Product__r.Spec__c);//产品规格
            data.put('invdm', r.Product__r.SerialNo__c);//助记码(产品代码)
            data.put('corpcode', ro.corpcode__c);//公司编号
            data.put('corpname', ro.corpname__c);//公司名称
            data.put('custcode', ro.custcode__c);//客户编号
            data.put('custname', ro.custname__c);//客户名称
            data.put('dbilldate', Utils.date2String(ro.CreatedDate,Utils.DATETIME_FORMAT_STR));//制单日期
            data.put('dbillcode', ro.ReturnRelationExhouse__r.Name);//来源出库订单号
            data.put('cgeneralhid', ro.cgeneralhid__c);//来源出库订表头pk
            //key = ro.ExWarehouse__r.Name + '-' + ro.Product__r.NCCode__c;
            data.put('cgeneralbid', r.Name);//来源出库明细订表体pk
            data.put('vbatchcode', r.vbatchcode__c);//批次号
            data.put('ts', Utils.date2String(ro.LastModifiedDate,Utils.DATETIME_FORMAT_STR));//最后更新时间
            data.put('opertype','1');//操作类型
            datas.add(data);
        }
         
                    
            Map<String ,List<Map<String,String>>>d = new Map<String ,List<Map<String,String>>>();
d.put('data',datas);
           // System.debug('暗号');
            String body = JSON.serialize(d);
           // System.debug(body);
//return body;
            HttpRequest req = new HttpRequest();
            req.setBody(body);
          //return body;
            req.setMethod('POST');
            req.setHeader('Content-Type','text/plain');
            // 接口写在自定义标签的quoteUrl里面
            req.setEndpoint(System.Label.quoteRejectGoodUrl);

            
            HttpResponse res = Utils.postRequest(req, 3);
             //System.debug(res.getBody());
               
            if (res.getStatusCode() == 200) {
                 //如果是测试
                if(Test.isRunningTest()){
                    return 'success';
                }
               // System.debug('========='+res.getBody());
                Map<String,Object> r = (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
               if(r.get('code') == 0 || r.get('code') == '0'){
               Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
            if( rs.get('result') == 0 ){
                        return '同步失败:' +(String) rs.get('result_msg');
                }else{
                        //解析json
                        Map<String,Object> da =(Map<String,Object>) rs.get('data');
                   Map<String ,Object> dataPk =(Map<String,Object>) da.get('dataPk'); 
                        String mainpk = (String)dataPk.get('pk_apply');

                        List<Object> sons = ( List<Object>)dataPk.get('so_apply_b');
                        Map<String ,String> bids= new Map<String ,String>();
                        for (Object bid: sons ){
                            map<String,Object> b = (map<String,Object>)bid;
                            bids.put((String)b.get('bid'),(String)b.get('pk_apply_b'));
                         }
                     //  System.debug(mainpk);
///更新ro ;
                        ro.Name = mainpk;
                        update ro ;
                        //更新detail 
                        for(ExWarehouse_Detail__c exd:hasDetails){
                          if(bids.containsKey(exd.Id)){
                          exd.Name = bids.get(exd.Id);
                          }
                        }
                        update hasDetails;
                return'同步成功';
                }
               }else{
               return (String)r.get('msg');
               }
                return 'OK';
            } else {
                return res.toString();
            }

        } catch (Exception e) {
           //保存数据失败，回滚事务
            //Database.rollback(sp);
            return e.getMessage();
        }
    }
    /*
     @future(callout=true)
     webservice static void syctonc (List<Id> eids){
    
     if(eids.size()>0){
         
         
         List<ExWarehouse__c> es = [select Id,Name from ExWarehouse__c where id in : eids];
      try{  

    
        
        //获取退货订单明细
        List<ExWarehouse_Detail__c> hasDetails = [select Id,Name,vbatchcode__c,Product__c,
                                                  ReturnNum__c ,Product__r.Name,Product__r.NCCode__c,Product__r.Model__c,
                                                  Product__r.Spec__c,Product__r.SerialNo__c,
                                                  ExWarehouse__c,ExWarehouse__r.Name,ExWarehouse__r.Finance__c,
                                                  ExWarehouse__r.ApprovalPerson__c,ExWarehouse__r.TransferNumber__c,
                                                  ExWarehouse__r.invoiceNumber__c,ExWarehouse__r.Contact__c,
                                                  ExWarehouse__r.ReturnReason__c,ExWarehouse__r.returnTransportFee__c,
                                                  ExWarehouse__r.ReturnOtherReason__c,
                                                  ExWarehouse__r.ApprovalDate__c,
                                                  ExWarehouse__r.CreatedBy.Name,
                                                  ExWarehouse__r.Applicant__c,
                                                  ExWarehouse__r.ck__c,ExWarehouse__r.ckname__c,
                                                  ExWarehouse__r.corpcode__c,ExWarehouse__r.corpname__c,
                                                  ExWarehouse__r.custcode__c,ExWarehouse__r.custname__c,
                                                  ExWarehouse__r.CreatedDate,ExWarehouse__r.ReturnRelationExhouse__r.Name,
                                                  ExWarehouse__r.cgeneralhid__c,ExWarehouse__r.LastModifiedDate 
                                                  from ExWarehouse_Detail__c where ExWarehouse__c in :eids] ;
        //获取用户信息
         User u = [select id,SubCompanyManager__r.name from User where id =: System.UserInfo.getUserId()];
        
         
        //保存要返回给调用者的数据集合
        List<Map<String,String>> datas = new List<Map<String,String>>();
        for(ExWarehouse_Detail__c r : hasDetails){
            Map<String,String> data = new Map<String,String>();
            //CRM数据
            data.put('id', r.ExWarehouse__c);//退货单id
            data.put('return_code', r.ExWarehouse__r.Name);//退货单号
            //data.put('dept_manager', u.SubCompanyManager__r.name);//部门经理
            data.put('finance', r.ExWarehouse__r.Finance__c);//财务部
            data.put('capproveid', r.ExWarehouse__r.ApprovalPerson__c == null ? '李波2':r.ExWarehouse__r.ApprovalPerson__c );//子公司总经理-审核人
            data.put('transfer_number', r.ExWarehouse__r.TransferNumber__c);//调拨单号
            data.put('invoice_number', r.ExWarehouse__r.invoiceNumber__c);//发票号
            data.put('applicant', r.ExWarehouse__r.Applicant__c);//申请人
            data.put('contact', r.ExWarehouse__r.Contact__c);//联系人
            //data.put('contact_dept', ro.ContactDept__c);//联系人部门
            //data.put('contact_phone', ro.ContactPhone__c);//联系人电话
           // data.put('contact_post', ro.ContactPost__c);//联系人职务
            
            //data.put('contact_date', ro.ContactDate__c!=null?Utils.date2String(ro.ContactDate__c,Utils.DATETIME_FORMAT_STR):'');//联系日期(日期)
            data.put('returnreason', r.ExWarehouse__r.ReturnReason__c);//退货原因 --> 备注
            data.put('nreturnfee',r.ExWarehouse__r.returnTransportFee__c.format());//客户退回运费
            data.put('return_reason_other', r.ExWarehouse__r.ReturnOtherReason__c);//其他原因说明 ??
            data.put('nnum', r.ReturnNum__c.format());//退货数量
           // data.put('is_return_invoice', ro.Is_Return_Invoice__c?'Y':'N');//是否退发票
            data.put('approved_date', r.ExWarehouse__r.ApprovalDate__c!=null?Utils.date2String(r.ExWarehouse__r.ApprovalDate__c,Utils.DATETIME_FORMAT_STR):'');//审核通过时间(日期时间)
            data.put('coperatorid',r.ExWarehouse__r.CreatedBy.Name);//制单人
            data.put('ckcode',r.ExWarehouse__r.ck__c);//仓库
            data.put('ckname',r.ExWarehouse__r.ckname__c);//仓库
            data.put('ctransmodeid','');//运输方式
            //NC数据
            data.put('bid',r.Id);//子表id;
            data.put('invname', r.Product__r.Name);//产品名称
            data.put('invcode', r.Product__r.NCCode__c);//产品代码
            data.put('invtype', r.Product__r.Model__c);//产品型号
            data.put('invspec', r.Product__r.Spec__c);//产品规格
            data.put('invdm', r.Product__r.SerialNo__c);//助记码(产品代码)
            data.put('corpcode', r.ExWarehouse__r.corpcode__c);//公司编号
            data.put('corpname', r.ExWarehouse__r.corpname__c);//公司名称
            data.put('custcode', r.ExWarehouse__r.custcode__c);//客户编号
            data.put('custname', r.ExWarehouse__r.custname__c);//客户名称
            data.put('dbilldate', Utils.date2String(r.ExWarehouse__r.CreatedDate,Utils.DATETIME_FORMAT_STR));//制单日期
            data.put('dbillcode', r.ExWarehouse__r.ReturnRelationExhouse__r.Name);//来源出库订单号
            data.put('cgeneralhid', r.ExWarehouse__r.cgeneralhid__c);//来源出库订表头pk
            //key = ro.ExWarehouse__r.Name + '-' + ro.Product__r.NCCode__c;
            data.put('cgeneralbid', r.Name);//来源出库明细订表体pk
            data.put('vbatchcode', r.vbatchcode__c);//批次号
            data.put('ts', Utils.date2String(r.ExWarehouse__r.LastModifiedDate,Utils.DATETIME_FORMAT_STR));//最后更新时间
            data.put('opertype','1');//操作类型
            datas.add(data);
        }
         
                    
            Map<String ,List<Map<String,String>>>d = new Map<String ,List<Map<String,String>>>();
d.put('data',datas);
           // System.debug('暗号');
            String body = JSON.serialize(d);
           // System.debug(body);
//return body;
            HttpRequest req = new HttpRequest();
            req.setBody(body);
          //return body;
            req.setMethod('POST');
            req.setHeader('Content-Type','text/plain');
            // 接口写在自定义标签的quoteUrl里面
            req.setEndpoint(System.Label.quoteRejectGoodUrl);

            
            HttpResponse res = Utils.postRequest(req, 3);
             System.debug(res.getBody());
         ///es[0].addError('测试错误...');
            if (res.getStatusCode() == 200) {
                 //如果是测试
                if(Test.isRunningTest()){
                   // return 'success';
                }
               // System.debug('========='+res.getBody());
                Map<String,Object> r = (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                System.debug('同步失败:' +r);
              // ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,
                                    // '同步失败' + r));
               if(r.get('code') == 0 || r.get('code') == '0'){
               Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
            if( rs.get('result') == 0 ){
                        System.debug('同步失败:' +(String) rs.get('result_msg'));
                        //return '同步失败:' +(String) rs.get('result_msg');
                }else{
                        //解析json
                        Map<String,Object> da =(Map<String,Object>) rs.get('data');
                        Map<String ,Object> dataPk =(Map<String,Object>) da.get('dataPk'); 
                        String mainpk = (String)dataPk.get('pk_apply');
                        String eid = (String)dataPk.get('id');
                        List<Object> sons = ( List<Object>)dataPk.get('so_apply_b');
                        Map<String ,String> bids= new Map<String ,String>();
                        for (Object bid: sons ){
                            map<String,Object> b = (map<String,Object>)bid;
                            bids.put((String)b.get('bid'),(String)b.get('pk_apply_b'));
                         }
                   
                       
                       //es.Name = mainpk;
                       for (ExWarehouse__c e : es){
                          System.debug(e.Id + ' ' + eid);
                       	if(e.Id == eid)e.Name = mainpk;
                       }
                       update es ;
                        //更新detail 
                        for(ExWarehouse_Detail__c exd:hasDetails){
                          if(bids.containsKey(exd.Id)){
                          exd.Name = bids.get(exd.Id);
                          }
                        }
                        update hasDetails;
                     System.debug('同步反写' + hasDetails.size());
                       
                //return'同步成功';
                }
               }else{
               //return (String)r.get('msg');
               }
              //  return 'OK';
            } else {
               /// return res.toString();
            }

        } catch (Exception e) {
          System.debug('同步异常' + e.getMessage());
           //保存数据失败，回滚事务
            //Database.rollback(sp);
           // return e.getMessage();
        }
     }
       // return '';
    
    }
    */
   /* 
global class NCResults {
    global List<NCResult> result;
        global String code;
        global String msg;
    } 
    global class NCResult {
    global String result;
        global String result_msg;
    }
    */

         
}